package wangxiaotao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import wangxiaotao.aop.annotation.Log;
import wangxiaotao.bean.vo.RoleVO;
import wangxiaotao.common.CommonResult;
import wangxiaotao.converter.RoleConverter;
import wangxiaotao.entity.Role;
import wangxiaotao.entity.RolePermissionRel;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/role")
public class RoleController extends BaseController{
    private final RoleConverter roleConverter;

    /**
     * 获取所有角色信息 不包括权限
     * @return
     */
    @RequiresRoles(value = {"sadmin", "admin", "semployee"}, logical = Logical.OR)
    @GetMapping("/listSimple")
    @Log
    public CommonResult getAllRoleSimple() {
//        List<Role> roleList = adminService.queryAllRoleAndPermission();
        List<RoleVO> roleVOList = roleService.list().stream()
                .map(s -> new RoleVO(s.getRoleId(),s.getRoleName(),s.getRoleDesc())).collect(Collectors.toList());
        return CommonResult.success(roleVOList);
    }

    /**
     * 获取所有角色信息 包括权限id
     * @return
     */
    @RequiresRoles(value = {"sadmin", "admin", "semployee"}, logical = Logical.OR)
    @GetMapping("/list")
    @Log
    public CommonResult getAllRole(String type, String data) {
        return CommonResult.success(adminService.queryAllRoleAndPermission(type,data));
    }

    /**
     * 添加角色
     * @param roleVO
     * @return
     */
    @RequiresRoles(value = {"sadmin", "admin"}, logical = Logical.OR)
    @PostMapping("/add")
    @Log
    public CommonResult addRole(@RequestBody @Validated RoleVO roleVO){
        Integer role_id = roleService.getObj(new QueryWrapper<Role>().select("max(role_id)"), s -> (Integer) s);
        Role role = roleConverter.toRole(roleVO);
        role.setRoleId(role_id+1);
        if (roleService.save(role))
            return CommonResult.success();
        return CommonResult.fail();
    }

    /**
     * 更新角色信息
     * @param roleVO
     * @return
     */
    @RequiresRoles(value = {"sadmin", "admin"}, logical = Logical.OR)
    @PostMapping("/update")
    @Log
    public CommonResult updateRole(@RequestBody @Validated RoleVO roleVO){
        Role role = roleConverter.toRole(roleVO);
        log.error(role.toString());
        if (roleService.updateById(role))
            return CommonResult.success();
        return CommonResult.fail();
    }

    /**
     * 修改角色的权限
     * @param roleId
     * @param permissionIds
     * @return
     */
    @PostMapping("/grantPermission/{roleId}")
    @Log
    public CommonResult grantPermissionByRoleId(@PathVariable Integer roleId,@RequestBody Integer[] permissionIds){
        //实际拥有的所有权限
        List<Integer> hasPermissions = rolePermissionRelService.listObjs(new QueryWrapper<RolePermissionRel>().select("permission_id").eq("role_id", roleId), s -> (Integer) s);
        //需要设置成的权限
        List<RolePermissionRel> setPermissions = Arrays.stream(permissionIds).map(s -> new RolePermissionRel(s, roleId)).collect(Collectors.toList());
        //判断将要设置的权限是否为空
        if (!hasPermissions.isEmpty())
            //删除存在的权限
            rolePermissionRelService.remove(new QueryWrapper<RolePermissionRel>().in("permission_id",hasPermissions).eq("role_id",roleId));
        if (!setPermissions.isEmpty())
            //保存设置的权限
            rolePermissionRelService.saveBatch(setPermissions);
        return CommonResult.success();
    }

    /**
     * 删除角色
     * @param roleId 角色id
     * @return
     */
    @GetMapping("/deleteRoleById")
    public CommonResult deleteRoleById(Integer roleId){
        //删除角色
        if (roleService.removeById(roleId))

            return CommonResult.success();
        return CommonResult.fail();
    }
}
